//
//  ZPOAuthViewController.swift
//  Weibo
//
//  Created by 张鹏 on 16/6/25.
//  Copyright © 2016年 张鹏. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class ZPOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 监听事件
    @objc private func cancelClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillClick(){
        let jsString = "document.getElementById('userId').value='15939113233',document.getElementById('passwd').value='252470184'"
        // JS注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    
    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector (ZPOAuthViewController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ZPOAuthViewController.autoFillClick))
        navigationItem.title = "OAuth登录"
    }
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }

    // MARK: -  懒加载控件
    private lazy var webView: UIWebView = {
        let view = UIWebView()
        view.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        print(url)
        let request = NSURLRequest(URL: url)
        view.loadRequest(request)
        return view
    }()
}

extension ZPOAuthViewController: UIWebViewDelegate {
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    // webView将要加载request
    // 如果返回true 代表 继续加载
    // 如果返回false  代表停止加载
    // 默认不实现 代表true
    func webview(webview: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        //判断urlstring 是否有值 而且 他的前缀是我们的回调页
        if let u = urlString where u.hasPrefix(REDIRECT_URI) {
            //请求参数键值对
            let query = request.URL?.query
            //可选值判断
            if let q = query {
                //字符串截取获得code
                let code = q.substringFromIndex("code=".endIndex)
                print("终于等到你还好我没放弃: \(code)")
                loadUserAccount(code)
                // 如果我们已经拿到code 就没必要继续加载
                return false
            }
        }
        
        return true
    }
}

extension ZPOAuthViewController {
    func loadUserAccount(code: String){
     
        ZPNetworktools.sharedTools.oauthLoadUserAccount(code, success: { (response) in
            //判断请求回来的res 是否有值 而且 是否可以转成一个字典
            //如果子在在判断可选值是否有值 可以转成你想要的类型 一般情况下 as?
            guard let res = response as? [String: AnyObject] else {
                print("返回的数据不是一个字典")
                return
            }
            //字典转模型
            let userAccount = ZPUserAccount(dict: res)
            
            self.loadUserInfo(userAccount)
        
            
            }) { (error) in
                print(error)
        }
    }





func loadUserInfo(userAccount: ZPUserAccount){
    ZPNetworktools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
        // 判断是否有值而且可以转成字典
        guard let res = response as? [String: AnyObject] else {
            return
        }
        
        userAccount.avatar_large = res["avatar_large"] as? String
        userAccount.screen_name = res["screen_name"] as? String
        // 通过归档保存数据
        ZPUserAccountTools.sharedTools.saveUserAccount(userAccount)
        print(userAccount)
        let reuslt = ZPUserAccountTools.sharedTools.userAccount
        print(reuslt)
    }) { (error) -> () in
        print("失败\(error)")
        }
    }
}


extension ZPOAuthViewController {
    func demo(){
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":"",
            "redirect_uri":REDIRECT_URI
        ]
        
        
        
        let manager = AFHTTPSessionManager()
        
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            
            // 判断请求回来的res 是否有值 而且 是否可以转成一个字典
            // 如果在在判断可选值是否有值 可以转成你想要的类型 一般情况下 as?
            guard let res = response as? [String: AnyObject] else {
                print("返回的数据不是一个字典")
                return
            }
            // 字典转模型
            let userAccount = ZPUserAccount(dict: res)
            print(userAccount)
        }) { (_, error) -> Void in
            print("失败:\(error)")
            SVProgressHUD.showErrorWithStatus("请求失败")
        }
    }
}






